
//
//  TableVerticalScrollView.swift
//  SmallParts
//
//  Created by 航汇聚 on 2019/10/10.
//  Copyright © 2019 BellaZhou. All rights reserved.
//

import UIKit

class TableVerticalScrollView: UITableView {
    var timer: Timer?
    let duration = 1.5
    var indexOfPage = 0
    let cellRowCount = 10
    
    func initTableConfig() {
        self.dataSource = self
        self.delegate = self
        self.isPagingEnabled = true
        self.register(UINib.init(nibName: "TableScrollCell", bundle: nil), forCellReuseIdentifier: "tableScrollCell")
    }
    func autoScrollByDuration(_ duration: TimeInterval) {
        let offsetWidth = self.bounds.size.width
        let offsetHeight = self.bounds.size.height
        let countOfScrollContentSubViews = cellRowCount
        timer = Timer.scheduledTimer(withTimeInterval: duration, repeats: true) { (timer) in
            var offsetPoint = CGPoint(x: 0, y: CGFloat(Float(offsetHeight)*Float(self.indexOfPage)))
            if self.indexOfPage > countOfScrollContentSubViews-1 {
                self.indexOfPage = 0
                offsetPoint = CGPoint(x: 0, y: 0)
                self.contentOffset = offsetPoint
            }else {
                self.scrollRectToVisible(CGRect(x: offsetPoint.x, y: offsetPoint.y, width: offsetWidth, height: offsetHeight), animated: true)
            }
            self.indexOfPage += 1
        }
        timer!.fire()
    }
}

extension TableVerticalScrollView: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cellRowCount
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableScrollCell", for: indexPath) as! TableScrollCell
        if indexPath.row % 2 == 0 {
            cell.backgroundColor = UIColor.cyan
        }else {
            cell.backgroundColor = UIColor.red
        }
        cell.testLabel?.text = "tableView实现轮播 \(indexPath.section)-\(indexPath.row)"
        return cell
    }
}
extension TableVerticalScrollView: UITableViewDelegate, UIScrollViewDelegate {
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        timer?.invalidate()
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.indexOfPage = Int(scrollView.contentOffset.y/scrollView.bounds.size.height)
        self.autoScrollByDuration(duration)
    }
}
